<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" >
      <el-form-item label="设备ID" prop="assetId" label-width="200px">
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 250px; gap: 250px "
        />
      </el-form-item>
      <el-form-item label="申请人ID" prop="userId" label-width="200px">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入申请人ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 250px; gap: 250px "
        />
      </el-form-item>
      <el-form-item label="审核人ID" prop="reviewerId" label-width="200px">
        <el-input
          v-model="queryParams.reviewerId"
          placeholder="请输入审核人ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 250px; gap: 250px "
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['assets:scrapAudit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scrapAuditList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="id" />
      <el-table-column label="资产ID" align="center" prop="assetId" width="180"/>
      <el-table-column label="申请人" align="center" prop="userId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.userId] || scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报废原因" align="center" prop="scrapReason" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            :style="{ backgroundColor: getStatusType(scope.row.status), color: 'white' }"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="reviewerId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.reviewerId] || scope.row.reviewerId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="reviewTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="reviewRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-if="scope.row.status === 0"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产报废审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改后的审核对话框 -->
    <el-dialog :title="approveTitle" :visible.sync="approveDialogVisible" width="400px" append-to-body>
      <el-form ref="approveForm" :model="approveScrapAudit" :rules="approveRules">
        <el-form-item label="审核备注">
          <el-input
            type="textarea"
            v-model="approveScrapAudit.reviewRemark"
            rows="4"
            placeholder="请输入审核备注（可选）"
          />
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="approveAction">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove">确 定</el-button>
        <el-button @click="approveDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listScrapAudit, getScrapAudit, delScrapAudit, addScrapAudit, updateScrapAudit,approveScrapRequest,rejectScrapRequest } from "@/api/assets/scrapAudit";
import {listUser} from "@/api/system/user";

export default {
  name: "ScrapAudit",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产报废审核表格数据
      scrapAuditList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetId: null,
        userId: null,
        applyTime: null,
        scrapReason: null,
        status: 0,
        reviewerId: null,
        reviewTime: null,
        reviewRemark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assetId: [
          { required: true, message: "资产ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "申请人ID不能为空", trigger: "blur" }
        ],
        applyTime: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ],
      },
      // 用户信息缓存
      userMap: {},
      // 新增审核相关变量
      approveDialogVisible: false,
      approveTitle: "",
      approveAction: "approve",
      // approveScrapAudit: null,
      approveScrapAudit: {
        id: null,
        assetId: null,
        userId: null,
        scrapReason: null,
        status: 0,
        reviewerId: null,
        reviewTime: null,
        reviewRemark: '' // 新增审核备注字段
      },
      approveRules: {
        reviewRemark: [
          { max: 200, message: "备注不能超过200字", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询资产报废审核列表 */
    getList() {
      this.loading = true;
      listScrapAudit(this.queryParams).then(response => {
        this.scrapAuditList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList() {
      listUser().then(response => {
        this.userMap = response.rows.reduce((map, user) => {
          map[user.userId] = user.userName;
          return map;
        }, {});
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assetId: null,
        userId: null,
        applyTime: null,
        scrapReason: null,
        status: null,
        reviewerId: null,
        reviewTime: null,
        reviewRemark: null
      };
      this.resetForm("form");
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '待审核';
        case 1:
          return '通过';
        case 2:
          return '拒绝';
        default:
          return '';
      }
    },
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'green'; // 通过状态使用绿色标签
        case 2:
          return 'red'; // 拒绝状态使用红色标签
        case 0:
          return '#FFD700'; // 待审核状态使用黄色标签
      }
    },
    // 新增审核相关方法
    handleApprove(row) {
      if (row.status !== 0) {
        this.$modal.msgWarning("该记录已审核，无法再次审核。");
        return;
      }
      this.approveScrapAudit = { ...row, reviewRemark: ''};
      this.approveTitle = "审核编号为'" + row.id + "'的报废请求";
      this.approveDialogVisible = true;
    },

    submitApprove() {
      if (this.approveAction === "approve") {
        this.handleApproveScrapRequest(this.approveScrapAudit);
      } else if (this.approveAction === "reject") {
        this.handleRejectScrapRequest(this.approveScrapAudit);
      }
      this.approveDialogVisible = false;
    },

    // 修改审核方法
    handleApproveScrapRequest(scrapAudit) {
      this.$modal.confirm('是否确认通过编号为"' + scrapAudit.id + '"的报废请求？').then(() => {
        return approveScrapRequest({
          id: scrapAudit.id,
          status: 1,
          assetId: scrapAudit.assetId,
          userId: scrapAudit.userId,
          applyTime: scrapAudit.applyTime,
          scrapReason: scrapAudit.scrapReason,
          reviewerId: this.userId,
          reviewTime: new Date(),
          reviewRemark: this.approveScrapAudit.reviewRemark  // 可添加审核备注字段
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核通过");
      }).catch(() => {});
    },

    handleRejectScrapRequest(scrapAudit) {
      this.$modal.confirm('是否确认拒绝编号为"' + scrapAudit.id + '"的报废请求？').then(() => {
        return rejectScrapRequest({
          id: scrapAudit.id,
          status: 2,
          assetId: scrapAudit.assetId,
          userId: scrapAudit.userId,
          applyTime: scrapAudit.applyTime,
          scrapReason: scrapAudit.scrapReason,
          reviewerId: this.userId,
          reviewTime: new Date(),
          reviewRemark: this.approveScrapAudit.reviewRemark  // 可添加审核备注字段
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核拒绝");
      }).catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产报废审核";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getScrapAudit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产报废审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScrapAudit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScrapAudit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除资产报废审核编号为"' + ids + '"的数据项？').then(function() {
        return delScrapAudit(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('assets/scrapAudit/export', {
        ...this.queryParams
      }, `scrapAudit_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
